package org.dna.wicketui.users;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.dna.MetroApplication;
import org.dna.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.wicket.util.crypt.Base64;

/**
 * Simple DB implementation of the Authenticator interface
 * @author andrea
 */
class DBAuthenticator implements IAccessAuthenticator {

    private static final Logger LOG = LoggerFactory.getLogger(DBAuthenticator.class.getName());

    public User authenticate(String username, String password) throws IllegalArgumentException {
        String encryptedPwd = encrypt(password, "UTF-8");
        LOG.debug("password: " + password + " SHA-1" + encryptedPwd);
        User user = findUser(username, encryptedPwd);
        if (user == null) {
            throw new IllegalArgumentException();
        }
        if (!user.getPassword().equals(encryptedPwd)) {
            throw new IllegalArgumentException();
        }
        return user;
    }

    private User findUser(String username, String password) {
        org.dna.metronomo.persistence.User dbUser = MetroApplication.get().getUserDAO().findUser(username, password);
        if (dbUser == null) {
            return null;
        }

        return new User(dbUser);
    }

    public static synchronized String encrypt(String plaintext, String encoding) {
        MessageDigest msgDigest = null;
        String hashValue = null;
        try {
            msgDigest = MessageDigest.getInstance("SHA-1");
            msgDigest.update(plaintext.getBytes(encoding));
            byte rawByte[] = msgDigest.digest();
            hashValue = new String(Base64.encodeBase64(rawByte));
        } catch (NoSuchAlgorithmException e) {
            LOG.error("Can't find SHA-1 algorithm", e);
        } catch (UnsupportedEncodingException e) {
            LOG.error("No encoding", e);
        }
        return hashValue;
    }
}
